<script setup lang="ts">
import { onMounted, ref } from "vue";
import { KeycloakInstance, KeycloakProfile } from "keycloak-js";
import Keycloak from "keycloak-js";

const keycloak = ref<null | KeycloakInstance>(null);
const message = ref("");
const username = ref<string | undefined>("");
const logout = () => {
  keycloak.value?.logout();
};

onMounted(() => {
  keycloak.value = Keycloak({
    url: "http://localhost:18080",
    realm: "keycloak-learn",
    clientId: "chapter-2",
  });
  keycloak.value
    .init({
      onLoad: "login-required",
    })
    .then((authenticated: boolean) => {
      keycloak.value?.loadUserProfile().then((profile: KeycloakProfile) => {
        username.value = profile.username;
      });
      message.value = `Authenticated: ${authenticated}`;
    })
    .catch(function () {
      message.value = "failed to initialize";
    });
});
</script>

<template>
  {{ message }}
  <hr />
  Hi {{ username }}
  <hr />
  <button @click="logout">Logout</button>
</template>
